package com.gec.it.util;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.util.List;

@Component
public class EmailUtil {
    @Autowired
    private JavaMailSenderImpl mailSender;
    //发送简单邮件(纯文字)
    public void sendMail(String to,String subject,String content){
        SimpleMailMessage m=new SimpleMailMessage();
        m.setFrom(mailSender.getUsername());//发送人
        m.setTo(to);//目的邮箱
        m.setSubject(subject);//标题
        m.setText(content);
        mailSender.send(m);
        System.out.println("邮件发送完毕");
    }

    //带复杂格式的邮件
    public void sendMail(String to, String subject, String html, List<String> filePaths)  {
        try {
            MimeMessage mm = mailSender.createMimeMessage();//复杂的邮件格式(可以带文件)
            MimeMessageHelper helper = new MimeMessageHelper(mm, true, "utf-8");
            helper.setFrom(mailSender.getUsername());
            helper.setTo(to);
            helper.setSubject(subject);//标题
            helper.setText(html, true);
            if(filePaths!=null) {
                for (String f : filePaths) {
                    File file = new File(f);
                    helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
                }
            }
            mailSender.send(mm);
            System.out.println("邮件发送完毕");
        }catch (Exception ex){
            throw new RuntimeException(ex);
        }
    }

}
